<template>
  <view class="con">
    <view class="nav" v-if="!isNoCheckBox"> <u-icon name="arrow-left" @click="goBack" color="#000" bold></u-icon>{{ filesInfo?.name }} </view>
    <view class="nav" v-else>
      <u-icon name="arrow-left" @click="isNoCheckBox = false" color="#000" bold></u-icon> 已选中{{ totalNumber }}个文件
      <text @click="checkAll(isCheckAll)"> {{ isCheckAll ? "全选 " : "取消全选" }} </text>
    </view>
    <view class="subTit">{{ fileCount.imageCount }}照片 {{ fileCount.videoCount }}视频</view>
    <view class="imgBox">
      <view class="top">
        <view class="tab">
          <view :class="{ item: true, active: tabActive === '1' }" @click="tabClick('1')">图片</view>
          <view :class="{ item: true, active: tabActive === '2' }" @click="tabClick('2')">视频</view>
        </view>
      </view>
      <template v-if="imgList.length > 0">
        <view class="list" v-for="(item, index) in imgList" :key="index">
          <view>
            <checkbox-group @change="itemCheckAll(index, $event)">
              <label>
                <view class="tit">
                  <checkbox
                    v-if="isNoCheckBox"
                    style="transform: scale(0.8)"
                    :value="item.isCheck"
                    :checked="item.isCheck"
                    activeBackgroundColor="#3b70fd"
                    iconColor="#fff"
                    activeBorderColor="#3b70fd"
                  />
                  {{ item.date }}
                </view>
              </label>
            </checkbox-group>
          </view>
          <checkbox-group @change="itemCheck(index, $event)">
            <view class="imgList">
              <view class="vI" v-for="(i, j) in item.files" :key="j">
                <checkbox v-if="isNoCheckBox" class="cb" :checked="i.checked" :value="i.id + ''" activeBackgroundColor="#3b70fd" iconColor="#fff" activeBorderColor="#3b70fd" />
                <image
                  v-if="i.fileType === '1'"
                  @click="
                    TanPreviewImage(
                      item.files.map((j: any) => j.url),
                      j
                    )
                  "
                  :src="i.url"
                  mode="aspectFill"
                />
                <video v-if="i.fileType === '2'" :show-play-btn="true" :show-fullscreen-btn="true" :src="i.url"></video>
                <view class="zz" :controls="false" v-if="i.fileType === '2'" @click="showVideoFn(i.url)"></view>
              </view>
            </view>
          </checkbox-group>
        </view>
      </template>
      <view v-else style="width: 100%; display: flex; justify-content: center">
        <u-empty mode="list"></u-empty>
      </view>
    </view>
    <view class="plus" @click="goPage('/pages/cloudStorage/sendPicture')"><u-icon name="plus" size="26" color="#fff" bold></u-icon></view>

    <view class="buttomBox">
      <view class="fun" v-if="!isNoCheckBox" @click="goPage(`/pages/cloudStorage/newfiles?id=${filesInfo.id}`)">
        <image src="../../static/my/bj.png" mode="aspectFill" />
        <view class="txt">编辑</view>
      </view>
      <view class="fun" v-if="!isNoCheckBox" @click="toogleFn">
        <image src="../../static/my/plgl.png" mode="aspectFill" />
        <view class="txt">批量管理</view>
      </view>
      <view class="fun" v-if="isNoCheckBox" @click="download">
        <image src="../../static/my/xz.png" mode="aspectFill" />
        <view class="txt">下载</view>
      </view>
      <view class="fun" v-if="isNoCheckBox" @click="delFn">
        <u-icon name="trash" size="28" color="#fff"> </u-icon>
        <view class="txt">删除</view>
      </view>
    </view>
    <u-overlay :show="videoShow" opacity="1" :mask-click-able="false">
      <view class="show">
        <video :show-play-btn="true" object-fit="cover" autoplay :show-fullscreen-btn="true" :src="showUrl"></video>
        <view class="icon l" @click="videoShow = false"><u-icon name="close" bold color="#FFf"></u-icon></view>
        <view class="icon r" @click="share"><image src="../../static/home/zf.png" mode="aspectFill" /></view>
      </view>
    </u-overlay>
  </view>
</template>
<script setup lang="ts">
import { deleteFiles, filesCount, getFilesList } from "@/api/cloudStorage";
import { useFilesStore } from "@/stores/files";
import { goBack, goPage, TanPreviewImage } from "@/utils/commonFn";
import { computed, ref } from "vue";
//@ts-ignore
import { onShow, onReachBottom, onBackPress } from "@dcloudio/uni-app";
const videoShow = ref(false);
const isNoCheckBox = ref(false);
const tabActive = ref("1");
const showUrl = ref("");
const isCheckAll = ref(true);
const { filesInfo } = useFilesStore();
const tabClick = (value: "1" | "2") => {
  tabActive.value = value;
  getFile();
};
const fileCount = ref({
  folderCount: 0,
  imageCount: 0,
  videoCount: 0,
});
onShow(async () => {
  const res1 = await filesCount({
    folderId: filesInfo.id,
  });
  fileCount.value = res1.data;
  getFile();
});
const getFile = async () => {
  const res: any = await getFilesList({
    id: filesInfo.id,
    fileType: tabActive.value,
    pageNum: page.value,
  });
  res.rows.forEach((item: any) => {
    item.isCheck = false;
    item.files.forEach((i: any) => {
      i.checked = false;
    });
  });
  imgList.value = res.rows;
};
const pageStatus = ref("loadmore");
const page = ref(1);
const imgList = ref<any[]>([]);
const showVideoFn = (url: string) => {
  showUrl.value = url;
  videoShow.value = true;
};
const getList = async () => {
  if (pageStatus.value == "nomore") {
    return;
  }
  pageStatus.value = "loadmore";
  const res: any = await getFilesList({
    id: filesInfo.id,
    fileType: tabActive.value,
    pageNum: page.value,
  });
  res.rows.forEach((item: any) => {
    item.isCheck = false;
    item.files.forEach((i: any) => {
      i.checked = false;
    });
  });
  imgList.value = imgList.value.concat(res.rows);

  if (imgList.value.length >= (res.total as number)) {
    pageStatus.value = "nomore";
  } else {
    pageStatus.value = "loadmore";
  }
};
onReachBottom(() => {
  page.value++;
  getList();
});

const toogleFn = () => {
  isNoCheckBox.value = !isNoCheckBox.value;
};
// 计算选择个数
const totalNumber = computed(() => {
  let arrs = getCheck();
  return arrs.length;
});
// 获取选中文件
const getCheck = () => {
  let arrs: any = [];
  imgList.value.forEach((item) => {
    item.files
      .filter((i: any) => i.checked)
      .forEach((j: any) => {
        arrs.push(j);
      });
  });
  return arrs;
};
//  全选
const checkAll = (value: boolean) => {
  isCheckAll.value = !isCheckAll.value;
  if (value) {
    imgList.value.forEach((item) => {
      item.isCheck = true;
      item.files.forEach((o: any) => (o.checked = true));
    });
  } else {
    imgList.value.forEach((item) => {
      item.isCheck = false;
      item.files.forEach((o: any) => (o.checked = false));
    });
  }
};
// 单个点击全选
const itemCheckAll = (index: number, event: any) => {
  const checked = event.detail.value;

  if (checked.length > 0) {
    imgList.value[index].files.forEach((o: any) => (o.checked = true));
  } else {
    imgList.value[index].files.forEach((o: any) => (o.checked = false));
  }
};
// 单个点击选择
const itemCheck = (index: number, v: any) => {
  const values: string[] = v.detail.value;
  console.log(values);

  if (values.length <= 0) {
    imgList.value[index].isCheck = false;
    return;
  }
  imgList.value[index].files.forEach((i: any) => {
    console.log(i.id);

    i.checked = values.includes(i.id + "");
  });
  imgList.value[index].isCheck = imgList.value[index].files.every((i: any) => i.checked);
};
const download = () => {
  console.log(getCheck());
  const arrs = getCheck();
  arrs.forEach((item: any) => {
    uni.showLoading({
      title: "下载中...",
    });
    uni.downloadFile({
      url: item.url, //分享的图片的链接
      success: (res) => {
        uni.getFileSystemManager().saveFile({
          tempFilePath: res.tempFilePath,
          success(res) {
            //保存图片
            if (item.fileType === "1") {
              uni.saveImageToPhotosAlbum({
                filePath: res.savedFilePath,
              });
            } else if (item.fileType) {
              uni.saveVideoToPhotosAlbum({
                filePath: res.savedFilePath,
              });
            }
          },
        });
      },
      complete() {
        //隐藏loading
        uni.hideLoading();
      },
      fail(err) {
        console.log(err, "shareImg");
      },
    });
  });
};
const delFn = async () => {
  let arr: any[] = getCheck();
  if (arr.length <= 0) {
    uni.showToast({
      title: "请选择图片/视频",
      icon: "none",
    });
    return;
  }
  uni.showModal({
    title: "提示",
    content: "您确定要删除吗？",
    success: async function (res) {
      if (res.confirm) {
        await deleteFiles({
          folderId: filesInfo.id,
          fileId: arr.map((i: any) => i.id),
        });
        uni.showToast({
          title: "删除成功",
          icon: "success",
          position: "top",
          success() {
            setTimeout(() => {
              pageStatus.value = "loadmore";
              imgList.value = [];
              getList();
            }, 300);
          },
        });
      }
    },
  });
};
const share = () => {
  console.log(showUrl.value, "分享");
  uni.downloadFile({
    url: showUrl.value,
    success(res: any) {
      //@ts-ignore
      wx.shareVideoMessage({
        videoPath: res.tempFilePath,
        success() {},
        fail: console.error,
      });
    },
    fail: console.error,
  });
};
</script>
<style lang="less" scoped>
.con {
  background: linear-gradient(170deg, #ccd9fb 0%, #ffffff 100%);
  padding-bottom: 0;
}
.nav {
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  gap: 30rpx;
}
.subTit {
  font-size: 28rpx;
  color: #3d3d3d;
  padding-left: 80rpx;
  padding-top: 30rpx;
}
.imgBox {
  background: #ffffff;
  border-radius: 32rpx 32rpx 0rpx 0rpx;
  padding-bottom: 130rpx;
  margin-top: 32rpx;
  .top {
    padding: 26rpx 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tab {
      display: flex;
      align-items: center;
      gap: 50rpx;
      .item {
        font-size: 28rpx;
        color: #3d3d3d;
        padding: 6rpx 30rpx;
        border-radius: 56rpx;
      }
      .active {
        background: #f1f4ff;
        color: #3b70fd;
      }
    }
    .right {
      width: 48rpx;
      height: 48rpx;
    }
  }
  .list {
    padding: 0 8rpx;
    .tit {
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #000000;
      padding: 12rpx 22rpx;
    }
    .imgList {
      display: flex;
      flex-wrap: wrap;
      gap: 4rpx;
      .vI {
        width: 184rpx;
        height: 184rpx;
        position: relative;
        position: relative;
        image,
        video {
          width: 100%;
          height: 100%;
        }
        .zz {
          width: 184rpx;
          height: 184rpx;
          position: absolute;
          left: 0;
          top: 0;
          z-index: 9;
        }
        .cb {
          position: absolute;
          left: 14rpx;
          top: 18rpx;
          z-index: 77;
          transform: scale(0.8);
          z-index: 999;
        }
      }
    }
  }
}
.buttomBox {
  background: #3b70fd;
  display: flex;
  justify-content: space-between;
  padding: 20rpx 188rpx;
  .fun {
    text-align: center;
    font-size: 28rpx;
    color: #ffffff;
    image {
      width: 48rpx;
      height: 48rpx;
    }
  }
}
:deep(checkbox) {
  border-radius: 50rpx !important;
  background: none;
}
.show {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  position: relative;
  video {
    width: 100%;
    height: 70%;
  }
  .icon {
    position: absolute;
    bottom: 50rpx;
    width: 64rpx;
    height: 64rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #1a1a1a;
  }
  .l {
    left: 30rpx;
  }
  .r {
    right: 30rpx !important;
    background: none;

    image {
      width: 64rpx;
      height: 64rpx;
    }
  }
}
</style>
